package prototech.ahedra.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import prototech.ahedra.form.LoginForm;
import prototech.ahedra.model.Usuario;
import prototech.ahedra.model.UsuarioDao;

public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		LoginForm frm = (LoginForm) form;
		String status = null;
		
		Usuario usr = UsuarioDao.GetUsuarioUsr(frm.getUsr());
		if ((usr != null) &&  usr.getPass().equals(frm.getPass())){
				HttpSession session = request.getSession();
				session.setAttribute("user", usr);
				status="success";				
		}
		else{
			ActionErrors errors = null;
			errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);				
			if (errors == null) {
				errors = new ActionErrors();
			}				
			errors.add("userRequired", new ActionMessage("login.datosNoValidos"));
			request.setAttribute(Globals.ERROR_KEY, errors); 
			status="fail";			
		}
		return mapping.findForward(status);
	}
}
